let myRequest = require('./myRequest.js');
let api = require('./api.js');
/**
 * Promise封装wx.checkSession
 */
function checkSession() {
  return new Promise(function (resolve, reject) {
    wx.checkSession({
      success: function () {
        resolve(true);
      },
      fail: function () {
        reject(false);
      }
    })
  });
}
/**
 * Promise封装wx.login
 */
function login() {
  return new Promise(function (resolve, reject) {
    wx.login({
      success: function (res) {
        if (res.code) {
          resolve(res);
        } else {
          reject(res);
        }
      },
      fail: function (err) {
        reject(err);
      }
    });
  });
}
/**
 * 调用微信登录
 */
function loginByWeixin() {
  return new Promise(function (resolve, reject) {
    return login().then((res) => {
      let data = {
        code: res.code
      }
      //登录远程服务器
      myRequest.EasyHttp.post(api.reqUrls.miniLogin, data).then(res => {
        if (res.data.status == 1) {
          wx.clearStorageSync()
          //存储用户信息
          wx.setStorageSync('token', res.data.result.token)
          resolve(res);
        } else {
          reject(res);
        }
      }).catch((err) => {
        reject(err);
      });
    }).catch((err) => {
      reject(err);
    })
  });
}
/**
 * 判断用户是否登录
 */
function checkLogin() {
  return new Promise(function (resolve, reject) {
    if (wx.getStorageSync('token')) {
      resolve(true);
    } else {
      reject(false);
    }
  });
}
module.exports = {
  loginByWeixin,
  checkLogin,
}